import { removeItem } from "@/util";
class listenEm {
  constructor() {
    this.dep_set = new Set();
    this.dep = [];
  }
  push(vm) {
    if (!this.dep_set.has(vm)) {
      this.dep.push(vm);
      this.dep_set.add(vm);
    }
  }
  remove(vm) {
    if (this.dep_set.delete(vm)) {
      this.dep = removeItem(this.dep, e => e !== vm);
    }
  }
  run() {
    this.dep.forEach(vm => {
      vm._setFontSize && vm._setFontSize();
    });
  }
}
window._listenEm = new listenEm();
const em = {
  mounted() {
    _listenEm.push(this);
    this.$nextTick(() => {
      this._setFontSize();
    });
    // 监听浏览器窗口变化
    window.addEventListener("resize", () => {
      this.$nextTick(() => {
        this._setFontSize();
      });
    });
  },
  beforeDestroy() {
    _listenEm.remove(this);
  },
  methods: {
    _setFontSize() {
      const parentNode = this.$el.parentNode;
      const width =
        parentNode.style.width ||
        parentNode.clientWidth ||
        parentNode.offsetWidth ||
        parentNode.scrollWidth;
      const config = this.$data.$_aspectRatio;
      if (parentNode && width && config && this.$el && this.$el.style) {
        // console.log(width, "config.width", config.width);
        const res = width / config.width;
        this.$_fontSizeRatio = res;
        const fontSize = res * 24;
        // console.log("计算", res);
        this.$el.style["transform"] = `scale(${fontSize / 24})`;
        this.$el.style["transformOrigin"] = `left top`;
      }
    }
  }
};
// console.log(em);
export { em };
